import { version } from 'react';
import * as THREE from 'three';
import vertex from './vertex.glsl';
import fragment from './fragment.glsl'
import gsap from 'gsap'
export class FlyLineShader {
  // 1.创建曲线
  lineCurve: THREE.CatmullRomCurve3 | null = null;
  geometry: THREE.BufferGeometry | null = null;
  shaderMaterial: THREE.ShaderMaterial | null |any= null;
  mesh: THREE.Points | null = null;
  z11: THREE.Texture | null = null;
  constructor(position = { x: 10 ,z: 0 },color=0x00ffff) {

     // 根据点生成曲线
     let linePoints = [
      // new THREE.Vector3(0, 0, 0),
      //  new THREE.Vector3(position.x / 2, 4, position.z / 2),
     
      // new THREE.Vector3(position.x , 0, position.z),
      
      // new THREE.Vector3(0, 0, 0),
      // new THREE.Vector3(-5, 4, 0),
      // new THREE.Vector3(-10,0, 0),

      new THREE.Vector3(0, 0, 0),
      new THREE.Vector3(position.x / 2, 4, position.z / 2),
      new THREE.Vector3(position.x, 0, position.z),
     
  
    
     
    ];
    // 创建曲线
    this.lineCurve = new THREE.CatmullRomCurve3(linePoints,true);
    const points = this.lineCurve.getPoints(1000);
    

    // 创建几何顶点
    this.geometry = new THREE.TubeBufferGeometry().setFromPoints(points)


     // 给每一个顶点设置属性

    const aSizeArray = new Float32Array(points.length );
    for (let i = 0; i < aSizeArray.length; i++) {
       aSizeArray[i] = i;
        
    }
   
    this.geometry.setAttribute('aSize',new THREE.BufferAttribute(aSizeArray,1));
  
    // 设置着色器材质
    this.shaderMaterial = new THREE.ShaderMaterial({ 
        uniforms: {
          uTime:{
            value:0
          },
          uColor:{
            value:new THREE.Color(color)
          },
          uLength:{
            value:points.length
          }
           
        },
        vertexShader:vertex,
        fragmentShader:fragment,
        transparent:true,
        // 关闭深度叠加检测
        depthWrite:false,
        blending:THREE.AdditiveBlending
    })

    this.mesh = new THREE.Points(this.geometry,this.shaderMaterial)

    gsap.to(this.shaderMaterial.uniforms.uTime,{
      value:1000,
      duration:2,
      repeat:-1,
      ease:'none'
    })
  }
  remove(){
    this.mesh?.remove()
    this.mesh?.removeFromParent()
    this.mesh?.geometry.dispose();
    (this.mesh?.material as any).dispose()
  }
}
